<template>
  <div class="menus-manage">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/home/prolist' }">项目列表</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/home/prolist/proinfo' }">{{proinfo.proNo}}</el-breadcrumb-item>
        <el-breadcrumb-item>项目合同</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 立项信息 -->
        <div class="card-title">项目合同</div>
        <el-form label-width="100px" :model="contract" :rules="contractRules" ref="contract">
          <el-row :gutter="24">
            <el-col :span="12">
              <!-- 合同编号 -->
              <el-form-item label="合同编号" prop="conNo">
                <el-input v-model="contract.conNo" placeholder="请输入合同编号"></el-input>
              </el-form-item>
              <!-- 合同名称 -->
              <el-form-item label="合同名称" prop="conName">
                <el-input v-model="contract.conName" placeholder="请输入合同名称"></el-input>
              </el-form-item>
              <!-- 合同金额 -->
              <el-form-item label="合同金额" prop="money">
                <el-input placeholder="请输入具体金额" v-model="contract.money" onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')">
                  <template slot="prepend">￥</template>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 公司名称 -->
              <el-form-item label="公司名称" prop="comp">
                <el-select style="width:100%" v-model="contract.comp">
                  <el-option
                    v-for="key in compList"
                    :key="key.id"
                    :label="key.compName"
                    :value="[key.compId, key.compName]"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- 客户名称 -->
              <el-form-item label="客户名称" prop="cus">
                <el-select style="width:100%" v-model="contract.cus">
                  <el-option
                    v-for="key in cusList"
                    :key="key.id"
                    :label="key.cusName"
                    :value="[key.id,key.cusName]"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- 签订人 -->
              <el-form-item label="签订人" prop="signUser">
                <el-input v-model="contract.signUser" placeholder="请输入签订人姓名"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="选择文件">
            <input type="file" />
          </el-form-item>
          <!-- 备注说明 输入长度限制20-->
          <el-form-item label="备注说明" prop="note">
            <el-input
              type="textarea"
              placeholder="备注说明（20字以内）"
              :rows="3"
              maxlength="20"
              v-model="contract.note"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="card-line">
          <!-- 立即修改 -->
          <el-button type="primary" size="small" @click="onEdit" v-if="isEdit" :disabled="isSubmit">立即修改</el-button>
          <el-button type="primary" size="small" @click="onSubmit" v-if="!isEdit" :disabled="isSubmit">立即申请</el-button>
          <!-- 返回 -->
          <el-button size="small" style="float:right" @click="goBack">返回</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入员工选择框子组件
import userSel from '@/components/UserSel/index.vue';

export default {
  // 注入组件
  components: {
    userSel
  },
  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },
  // 当前实例数据
  data () {
    return {
      isEdit: false,
      // 防止重复提交
      isSubmit: false,
      // 获取选中用户信息
      getUser: [],

      // 项目合同表单
      contract: {
        // 合同编号
        conNo: '',
        // 合同名称
        conName: '',
        // 合同金额
        money: '',
        // 关联公司
        comp: '',
        // 关联客户
        cus: '',
        // 签订人
        signUser: '',
        // 上传文件路径
        picUrl: '',
        // 备注说明
        note: ''
      },

      // 修改回显用户
      pmp: [],

      // 表单验证规则
      contractRules: {
        conNo: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
        conName: [
          { required: true, message: '请输入合同名称', trigger: 'blur' }
        ],
        money: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
        comp: [{ required: true, message: '请选择公司', trigger: 'change' }],
        cus: [{ required: true, message: '请选择客户', trigger: 'change' }]
      },

      // 所有公司数据
      compList: [],

      // 所有客户数据
      cusList: [],

      // 所有用户信息
      users: [],

      proinfo: {}
    };
  },

  // 创建实例后执行
  created () {
    this.getProinfo();

    // 查询所有公司
    this.getCompList();

    // 查询所有客户
    this.getCusList();

    // 获取所有员工
    this.getUserList();

    this.editCon();
  },

  methods: {

    // 修改项目合同信息
    editCon () {
      let row = this.$route.query.datas;
      if (row) {
        this.contract.id = row.id;
        this.contract.conNo = row.conNo;
        this.contract.conName = row.conName;
        this.contract.money = row.money;
        this.contract.comp = row.compName;
        this.contract.cus = row.cusName;
        this.contract.signUser = row.signUser;
        this.contract.note = row.note;
        this.contract.picUrl = row.picUrl;

        // 显示修改按钮
        this.isEdit = true;
      } else {
        return false;
      }
    },

    // 获取项目信息
    getProinfo () {
      let project = JSON.parse(sessionStorage.getItem('project'));
      this.proinfo = project;
    },

    // 获取选中用户信息
    selUser (data) {
      this.getUser = data;
      this.contract.signUser = data[0];
    },

    // 获取所有用户
    getUserList () {
      let _this = this;
      let params = {
        status: ''
      };
      _this.$http.post('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.users = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 查询所有公司
    getCompList () {
      this.$http.post('/api/findAllCompNoPage').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          this.compList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 查询所有客户
    getCusList () {
      this.$http.post('/api/findAllCus').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          this.cusList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    onEdit () {
      // 防止重复提交
      this.isSubmit = true;
      setTimeout(() => {
        this.isSubmit = false;
      }, 1000);

      // 收集请求数据
      let params = {
        id: this.contract.id,
        proId: this.proinfo.id,
        // 合同编号
        conNo: this.contract.conNo,
        // 合同名称
        conName: this.contract.conName,
        // 合同金额
        money: this.contract.money,
        // 关联公司
        compId: typeof (this.contract.comp) === 'string' ? this.$route.query.datas.compId : this.contract.comp[0],

        compName: typeof (this.contract.comp) === 'string' ? this.$route.query.datas.compName : this.contract.comp[1],
        // 关联客户
        cusId: typeof (this.contract.cus) === 'string' ? this.$route.query.datas.cusId : this.contract.cus[0],

        cusName: typeof (this.contract.cus) === 'string' ? this.$route.query.datas.cusName : this.contract.cus[1],
        // 签订人
        signUser: this.contract.signUser,
        // 上传文件路径
        picUrl: this.contract.picUrl,
        // 备注说明
        note: this.contract.note
      };

      this.$nextTick(() => {
        // 判断是否通过验证规则验证
        this.$refs['contract'].validate(valid => {
          if (valid) {
            let file = document.querySelector('input[type=file]').files[0];
            if (file) {
              this.updatefile();
            } else {
              this.updateCon(params);
            }
          }
        });
      });
    },

    // 文件上传  修改合同
    updatefile () {
      let file = document.querySelector('input[type=file]').files[0];
      let formData = new FormData(); // 创建form对象
      formData.append('uploadFile', file);

      this.$http.upload('api/uploadFile', formData).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          let cons = {
            id: this.contract.id,
            proId: this.proinfo.id,
            // 合同编号
            conNo: this.contract.conNo,
            // 合同名称
            conName: this.contract.conName,
            // 合同金额
            money: this.contract.money,
            // 关联公司
            compId: typeof (this.contract.comp) === 'string' ? this.$route.query.datas.compId : this.contract.comp[0],

            compName: typeof (this.contract.comp) === 'string' ? this.$route.query.datas.compName : this.contract.comp[1],
            // 关联客户
            cusId: typeof (this.contract.cus) === 'string' ? this.$route.query.datas.cusId : this.contract.cus[0],

            cusName: typeof (this.contract.cus) === 'string' ? this.$route.query.datas.cusName : this.contract.cus[1],
            // 签订人
            signUser: this.contract.signUser,
            // 上传文件路径
            picUrl: datas,
            // 备注说明
            note: this.contract.note
          };
          this.updateCon(cons);
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 修改合同
    updateCon (params) {
      // 添加项目合同
      this.$http.raw('api/updateContract', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$message({
            message: '修改成功！',
            type: 'success'
          });
          // 初始化弹窗表单数据
          this.$refs['contract'].resetFields();
          this.goBack();
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 文件上传
    file () {
      let file = document.querySelector('input[type=file]').files[0];
      let formData = new FormData(); // 创建form对象
      formData.append('uploadFile', file);

      this.$http.upload('api/uploadFile', formData).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          let cons = {
            proId: this.proinfo.id,
            // 合同编号
            conNo: this.contract.conNo,
            // 合同名称
            conName: this.contract.conName,
            // 合同金额
            money: this.contract.money,
            // 关联公司
            compId: this.contract.comp === undefined ? '' : this.contract.comp[0],

            compName: this.contract.comp === undefined ? '' : this.contract.comp[1],
            // 关联客户
            cusId: this.contract.cus[0],

            cusName: this.contract.cus === undefined ? '' : this.contract.cus[1],
            // 签订人
            signUser: this.contract.signUser,
            // 上传文件路径
            picUrl: datas,
            // 备注说明
            note: this.contract.note
          };
          this.saveCon(cons);
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 保存合同
    saveCon (params) {
      // 添加项目合同
      this.$http.raw('api/insertContract', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$message({
            message: '添加成功！',
            type: 'success'
          });
          // 初始化弹窗表单数据
          this.$refs['contract'].resetFields();
          this.goBack();
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 返回
    goBack () {
      this.$router.push({
        path: '/home/prolist/proinfo/',
        query: {
          tabs: 'first'
        }
      });
    },

    // 提交合同
    onSubmit () {
      // 防止重复提交
      this.isSubmit = true;
      setTimeout(() => {
        this.isSubmit = false;
      }, 1000);

      // 收集请求数据
      let params = {
        proId: this.proinfo.id,
        // 合同编号
        conNo: this.contract.conNo,
        // 合同名称
        conName: this.contract.conName,
        // 合同金额
        money: this.contract.money,
        // 关联公司
        compId: this.contract.comp === undefined ? '' : this.contract.comp[0],

        compName: this.contract.comp === undefined ? '' : this.contract.comp[1],
        // 关联客户
        cusId: this.contract.cus[0],

        cusName: this.contract.cus === undefined ? '' : this.contract.cus[1],
        // 签订人
        signUser: this.contract.signUser,
        // 上传文件路径
        picUrl: '',
        // 备注说明
        note: this.contract.note
      };

      this.$nextTick(() => {
        // 判断是否通过验证规则验证
        this.$refs['contract'].validate(valid => {
          if (valid) {
            let file = document.querySelector('input[type=file]').files[0];
            if (file) {
              this.file();
            } else {
              this.saveCon(params);
            }
          }
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
